<template>
  <div class="evaluation-container">
    <el-card>
      <div slot="header" class="header-container">
        <span>评价管理</span>
        <div class="header-right">
          <el-button 
            type="primary" 
            icon="el-icon-plus" 
            @click="handleAdd"
            v-if="evaluationType === 'sent'">
            发出评价
          </el-button>
          <el-radio-group v-model="evaluationType" @change="handleTypeChange">
            <el-radio-button label="received">收到的评价</el-radio-button>
            <el-radio-button label="sent">发出的评价</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      
      <el-table :data="evaluationList" v-loading="loading">
        <!-- 修改用户名称列 -->
        <el-table-column 
          prop="userName" 
          :label="userType === 'student' ? '企业名称' : '学生姓名'">
        </el-table-column>
        <el-table-column prop="content" label="评价内容" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="评价时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="评分" width="150">
          <template slot-scope="scope">
            <el-rate v-model="scope.row.score" disabled show-score></el-rate>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" v-if="evaluationType === 'sent'">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 评价编辑对话框 -->
      <el-dialog 
        :title="dialogType === 'add' ? '发出评价' : '编辑评价'" 
        :visible.sync="dialogVisible" 
        width="500px">
        <el-form :model="evaluationForm" ref="evaluationForm" :rules="rules">
          <!-- 添加用户选择 -->
          <el-form-item 
            :label="userType === 'student' ? '企业名称' : '学生姓名'" 
            prop="targetId"
            v-if="dialogType === 'add'">
            <el-select 
              v-model="evaluationForm.targetId" 
              filterable 
              placeholder="请选择">
              <el-option
                v-for="item in targetUserList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 添加职位选择
          <el-form-item label="职位" prop="jobId" v-if="dialogType === 'add'">
            <el-select 
              v-model="evaluationForm.jobId" 
              filterable 
              placeholder="请选择职位">
              <el-option
                v-for="item in jobList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="评分" prop="score">
            <el-rate v-model="evaluationForm.score" show-score></el-rate>
          </el-form-item>
          <el-form-item label="评价内容" prop="content">
            <el-input
              type="textarea"
              v-model="evaluationForm.content"
              :rows="4"
              placeholder="请输入评价内容">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvaluation">确定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'EvaluationList',
  data() {
    return {
      evaluationList: [],
      loading: false,
      evaluationType: 'received', // received: 收到的评价, sent: 发出的评价
      userType: '', // student: 学生, enterprise: 企业
      dialogVisible: false,
      dialogType: 'edit', // add: 新增, edit: 编辑
      targetUserList: [], // 可评价的用户列表
      jobList: [], // 职位列表
      evaluationForm: {
        id: null,
        targetId: '', // 评价对象ID
        jobId: '', // 职位ID
        score: 0,
        content: ''
      },
      rules: {
        targetId: [{ required: true, message: '请选择评价对象', trigger: 'change' }],
        jobId: [{ required: true, message: '请选择职位', trigger: 'change' }],
        score: [{ required: true, message: '请选择评分', trigger: 'change' }],
        content: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
      },
      page: 1,
      size: 10
    }
  },
  methods: {
    async fetchEvaluations() {
      try {
        this.loading = true
        const response = await this.$axios.get('/message/list', {
          params: {
            type: this.evaluationType === 'received' ? '1' : '0'
          }
        })
        if (response.data.code === 200) {
          // 修改数据处理逻辑，直接使用返回的数组
          this.evaluationList = response.data.data.map(item => ({
            id: item.id,
            fromUserId: item.fromUserId,
            toUserId: item.toUserId,
            content: item.content,
            score: item.score,
            createTime: item.createTime,
            userName: item.userName, // 添加用户名称
            type: item.type
          }))
        } else {
          this.$message.error(response.data.msg || '获取评价列表失败')
        }
      } catch (error) {
        this.$message.error('获取评价列表失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    handleTypeChange() {
      this.fetchEvaluations()
    },

    handleAdd() {
      this.dialogType = 'add'
      this.evaluationForm = {
        targetId: '',
        score: 0,
        content: ''
      }
      this.dialogVisible = true
      this.fetchTargetUsers()
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      this.evaluationForm = {
        id: row.id,
        score: row.score,
        content: row.content
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该评价?', '提示', {
          type: 'warning'
        })
        const response = await this.$axios.delete(`/message/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.fetchEvaluations()
        } else {
          this.$message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },

    async submitEvaluation() {
      try {
        await this.$refs.evaluationForm.validate()
        let response
        if (this.dialogType === 'add') {
          response = await this.$axios.post('/message/add', {
            toUserId: this.evaluationForm.targetId,
            score: this.evaluationForm.score,
            content: this.evaluationForm.content,
            type: this.userType === 'student' ? '1' : '0'
          })
        } else {
          response = await this.$axios.post('/message/edit', {
            id: this.evaluationForm.id,
            score: this.evaluationForm.score,
            content: this.evaluationForm.content
          })
        }

        if (response.data.code === 200) {
          this.$message.success(this.dialogType === 'add' ? '评价成功' : '更新成功')
          this.dialogVisible = false
          this.fetchEvaluations()
        } else {
          this.$message.error(response.data.msg || (this.dialogType === 'add' ? '评价失败' : '更新失败'))
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error((this.dialogType === 'add' ? '评价' : '更新') + '失败：' + error.message)
        }
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    getUserType() {
      // 从localStorage获取用户类型
      this.userType = localStorage.getItem('userType')
    },

    // 获取可评价的用户列表
    async fetchTargetUsers() {
      try {
        const response = await this.$axios.get('/jobSeeker/list1', {
          params: {
            type: 0,
            page1: 1,
            size: 100
          }
        })
        
        if (response.data.code === 200) {
          // 直接将字符串数组转换为所需的格式
          this.targetUserList = response.data.data.map((name, index) => ({
            id: index + 1, // 使用索引作为临时ID
            name: name
          }))
        } else {
          this.$message.error(response.data.msg || '获取学生列表失败')
        }
      } catch (error) {
        this.$message.error('获取学生列表失败：' + error.message)
      }
    },

    // 获取职位列表
    async fetchJobs() {
      try {
        const response = await this.$axios.get('/evaluation/jobs')
        if (response.data.code === 200) {
          this.jobList = response.data.data || []
        }
      } catch (error) {
        this.$message.error('获取职位列表失败：' + error.message)
      }
    }
  },
  created() {
    this.getUserType()
    this.fetchEvaluations()
  }
}
</script>

<style scoped>
.evaluation-container {
  padding: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.delete-btn {
  color: #F56C6C;
  margin-left: 10px;
}

.el-rate {
  margin-top: 5px;
}
</style> 